package com.zhsj.OkeHomeConsumption.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

/**
 * Created by rxy on 17/7/26.
 */

public class DownloadAppUtils {
    private static final String TAG = DownloadAppUtils.class.getSimpleName();
    public static long downloadUpdateApkId = -1;//下载更新Apk 下载任务对应的Id
    public static String downloadUpdateApkFilePath;//下载更新Apk 文件路径

    /**
     * 通过浏览器下载APK包
     * @param context
     * @param url
     */
    public static void downloadForWebView(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(uri);
        context.startActivity(intent);
    }


    /**
     * 下载更新apk包
     * 权限:1,<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
     * @param context
     * @param url
     */
    public static void downloadForAutoInstall(Context context, String url, String fileName, String title) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        downloadForWebView(context, url);
//        try {
//            Uri uri = Uri.parse(url);
//            DownloadManager downloadManager = (DownloadManager) context
//                    .getSystemService(Context.DOWNLOAD_SERVICE);
//            DownloadManager.Request request = new DownloadManager.Request(uri);
//            //在通知栏中显示
//            request.setVisibleInDownloadsUi(true);
//            request.setTitle(title);
//            String filePath;
//            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//外部存储卡
//                filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
//            } else {
////                .showShort(context, R.string.download_sdcard_error);
//                return;
//            }
//            downloadUpdateApkFilePath = filePath + File.separator + fileName;
//            // 若存在，则删除
//            deleteFile(downloadUpdateApkFilePath);
//            Uri fileUri = Uri.parse("file://" + downloadUpdateApkFilePath);
//            request.setDestinationUri(fileUri);
//            downloadUpdateApkId = downloadManager.enqueue(request);
//        } catch (Exception e) {
//            e.printStackTrace();
//            downloadForWebView(context, url);
//        }
    }


//    private static boolean deleteFile(String fileStr) {
//        File file = new File(fileStr);
//        return file.delete();
//    }

}
